package com.zerosoft.guotai.socket;

import com.zerosoft.guotai.mqtt.MqttSendClient;
import com.zerosoft.guotai.thread.ThreadPoolUtil;
import com.zerosoft.guotai.handler.SocketHandler;
//import jakarta.annotation.PostConstruct;
//import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
@Component
public class CustomSocketServer {
    @Value("${socket.port}")
    private Integer port;

    @Resource
    private MqttSendClient mqttSendClient;
    /**
     * 初始化调用接口
     *
     * 异步启动socket监听服务，端口 7777
     */
    @PostConstruct
    public void socketServerInit() throws IOException {
//        //测试checksum
//        byte[] retmsg = new byte[4];
//        ByteBuffer bb = ByteBuffer.wrap(retmsg);
//        bb.put((byte)0x7e);
//        bb.put((byte)0x04);
//        bb.put((byte)0x01);
//        bb.put(BufferToObjectConverter.calculateCheckSum(retmsg));
//        System.out.println(String.format("%x-%x-%x-%x",retmsg[0],retmsg[1],retmsg[2],retmsg[3]));
        new Thread(() -> {
            try {
                // 监听端口
                log.info("开始启动socket服务信息，端口监听 "+port);
                ServerSocket serverSocket = new ServerSocket(port);

                // 循环监听
                while (true) {
                    log.info("等待客户端连接...");
                    Socket clientSocket = serverSocket.accept();
                    ThreadPoolUtil.THREAD_POOL.execute(
                            // 构建handler
                            SocketHandler.builder().clientSocket(clientSocket).mqttSendClient(mqttSendClient).build()
                    );
                    log.info("客户端连接成功，当前连接数：{}", ThreadPoolUtil.THREAD_POOL.getActiveCount());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
